package com.hyt.it.ogt.ks.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.hyt.common.utils.result.Result;
import com.hyt.core.util.UUIDUtils;
import com.hyt.it.ogt.ks.config.ConfigManager;
import com.hyt.it.ogt.ks.config.KsBizRunTimeException;
import com.hyt.it.ogt.ks.enums.BizStatusCode;
import com.hyt.it.ogt.ks.feign.TpsClient;
import com.hyt.it.ogt.ks.model.dto.WxLoginResponseDTO;
import com.hyt.it.ogt.ks.model.vo.monitor.response.WxLoginVO;
import com.hyt.it.ogt.ks.service.IWebChatService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 刘恒活
 * @since 2021/7/22 9:53
 */
@Slf4j
@Service
public class WebChatServiceImpl implements IWebChatService {
    private static final int INT_EXPIRE_TIME = 30*60;
    @Resource
    private ConfigManager configManager;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private TpsClient tpsClient;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WxLoginVO wxLogin(String jsCode){
        WxLoginVO vo = new WxLoginVO();
        // 1.code2session返回JSON数据
        String json = tpsClient.wxLogin(jsCode);
        Result result = JSON.parseObject(json, Result.class);
        String resultJson = result.getObj().toString();
        // 2.解析数据
        WxLoginResponseDTO wxLoginResponseDTO = JSON.parseObject(resultJson, WxLoginResponseDTO.class);
        if(0 != wxLoginResponseDTO.getErrcode()) {
            // 您的登录已失效，请重新登录
            throw new KsBizRunTimeException(BizStatusCode.WX_LOGIN_INVALID.getCode());
        }
        // 3.保存登录信息，先从本地数据库中查找用户是否存在
        //TODO  4.返回自定义登陆态 Token
        vo.setToken(this.createMyWxToken(wxLoginResponseDTO.getOpenid(), wxLoginResponseDTO.getSession_key()));
        return vo;
    }

    /**
     * 需要全局失效拦截
     * @param wxOpenId
     * @param sessionKey
     * @return
     */
    private String createMyWxToken(String wxOpenId, String sessionKey) {
        String uuid = UUIDUtils.randomUUID();
        return uuid;
    }

}
